package sz.szsmk.citizencard.util;

import java.util.Map;
import java.util.TreeMap;

import sz.szsmk.citizencard.log.L;

public class SIgnUtil {

    /**
     * 创建签名
     *
     * @param map
     * @return
     */
    public static String createSign(Map<String, String> map, String key) {
        StringBuilder signsb = new StringBuilder();
        for (Map.Entry<String, String> e : map.entrySet()) {
            String value = e.getValue();
            if (null == value || value.length() <= 0) {
                continue;
            }
            if ("signature".equals(e.getKey())) {
                continue;
            }
            signsb.append(e.getKey());
            signsb.append("=");
            signsb.append(value);
            signsb.append("&");
        }
        signsb.append("key=" + key);
        return signsb.toString();
    }


    /**
     * 生成签名
     *
     * @param map
     * @param key 即token 其中英文要全部转为大写
     * @return
     */
    public static String generateSign(Map<String, String> map, String key) {
        String sign = createSign(map, key.toUpperCase());
        L.e(Constant.TAG, "sign-----------" + sign);
        String signature = Md5Util.md5Hash(sign).toUpperCase();
        return signature;
    }

    /**
     * 生成签名
     *
     * @param map
     * @param key 即token 其中英文要全部转为大写
     * @return
     */
    public static String generateAuthorSign(Map<String, String> map, String key) {
        String sign = createSign(map, key);
        L.e(Constant.TAG, "sign-----------" + sign);
        String signature = Md5Util.md5(sign,"").toUpperCase();
        return signature;
    }

    /**
     * 签名认证
     *
     * @param beanmap
     * @return
     */
    public static boolean checkSignature(String tokenDB, TreeMap<String, String> beanmap) {

        String signature = beanmap.get("signature");
        //数字签名signature验
        String retSign = Md5Util.md5Hash(SIgnUtil.createSign(beanmap, tokenDB.toUpperCase())).toUpperCase();
        if (!retSign.equals(signature)) {
            return false;
        }
        return true;
    }
}